const Qs = require('qs')
const path = require('path');
const colors = require('colors');
const { FFScene, FFAudio, FFAlbum, FFImage, FFCreator } = require("ffcreator");
const config = require('../../config/index')

class CreateVideo {
    async create(ctx, next) {
        // const bodyData = Qs.parse(ctx.request.body);
        // const bodyData = JSON.parse(ctx.request.body);
        const bodyData = ctx.request.body;
        // Create FFCreator instance 创建creator入口
        const creator = new FFCreator(config.creatorConfig);

        // 添加音乐
        // creator.addAudio(new FFAudio({
        //   path: config.audio,
        //   volume: 0.9,
        //   fadeIn: 4,
        //   fadeOut: 4,
        //   loop: true
        // }));

        // Create scene2 创建场景
        // const scene = new FFScene();
        // /**
        //  *  scene.setBgColor('#30336b');        // 设置背景色
        //  *  scene.setDuration(8.5);             // 设置停留时长
        //  *  scene.setTransition('Fat', 1.5);    // 设置过渡动画(类型, 时间)
        //  *  creator.addChild(scene);            // 将场景添加到creator入口
        //  */
        // // Create a multi-photo Album 创建相册元素 (动画只能单一设置)
        // const album = new FFAlbum({
        //     list: [
        //         'http://dev.mxy.chinamobo.com/cdn/certificate/a4_vertical/bg/bg1.png',
        //         'http://dev.mxy.chinamobo.com/cdn/certificate/a4_vertical/bg/bg2.png',
        //         'http://dev.mxy.chinamobo.com/cdn/certificate/a4_vertical/bg/bg3.png',
        //         'http://dev.mxy.chinamobo.com/cdn/certificate/a4_vertical/bg/bg4.png',
        //         'http://dev.mxy.chinamobo.com/cdn/certificate/a4_vertical/bg/bg5.png',
        //     ],   // Picture collection for album 图片列表
        //     x: config.albumWidth / 2,
        //     y: config.albumHeight / 2,
        //     width: config.albumWidth,
        //     height: config.albumHeight
        // });

        // album.setTransition('zoomIn');      // Set album switching animation 添加转场动画
        // album.setDuration(2);             // Set the stay time of a single sheet 停留秒数
        // scene.addChild(album);

        // scene.setDuration(album.getTotalDuration() + 1)
        // creator.addChild(scene);

        // 另一种实现方式
        // const piclist = [
        //     'https://img0.baidu.com/it/u=2805604174,586521884&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1697475600&t=660f7ff4648a889606806f503345757e',
        //     'https://img0.baidu.com/it/u=110176915,621401482&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1697475600&t=9d10fc9f41c283bc23dbf0ed9c2cbc59',
        //     'https://img0.baidu.com/it/u=1624963289,2527746346&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1697475600&t=6f043185c91fbe7da6eacedf153279cf',
        //     'https://img0.baidu.com/it/u=1064090962,1324491134&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        //     'https://img0.baidu.com/it/u=732498250,1887863602&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        //     'https://img1.baidu.com/it/u=3879509776,3900409493&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800',
        //     'https://img0.baidu.com/it/u=425356593,1233752699&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500',
        //     'https://img2.baidu.com/it/u=3454854132,2519077152&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
        //     'https://img0.baidu.com/it/u=859607673,960376049&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500',
        //     'https://img2.baidu.com/it/u=1540466220,1629404745&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500'
        // ]
        const piclist = JSON.parse(bodyData.list)
        const list = Array.from({ length: piclist.length }, (v, i) => (
            { 
                url: piclist[i % piclist.length],
                animat: i % 3 === 0 ? 'DreamyZoom' : i % 3 === 2 ? 'CrossZoom' : 'FilmBurn',
            }
        ))

        list.forEach(item => {
            const scene = new FFScene()

            const bg = new FFImage({
                path: item.url,
                x: config.albumWidth / 2,
                y: config.albumHeight / 2,
                width: config.albumWidth,
                height: config.albumHeight
            })
            bg.setBlur(40) // 添加模糊  值0-100
            const img = new FFImage({
                path: item.url,
                x: config.albumWidth / 2,
                y: config.albumHeight / 2,
                width: config.albumWidth,
                height: config.albumHeight
            })


            // 设置一个画面停留的时间，一个画面的动画，一个画面添加的元素，然后Compos添加这个画面，循环生成
            scene.setDuration(3) 
            scene.setTransition(item.animat)
            scene.addChild(bg)
            scene.addChild(img)
            creator.addChild(scene)
        })

        // 
        creator.output(path.join(__dirname, "../../public/hmm.mp4"));
        creator.start().then(res=>{
            console.log(res, 'res');
        });        // Start processing 开始创建视频
        creator.closeLog();     // Close log (including perf) 关闭log
        // 完成。
        creator.complete = function () {
            return new Promise(function (resolve, reject) {
                // 视频进度监听
                creator.on('start', () => {
                    console.log(`FFCreator start`);
                });
                creator.on('error', e => {
                    reject(false)
                    console.log(`FFCreator error: ${JSON.stringify(e)}`);
                });
                creator.on('progress', e => {
                    console.log(colors.yellow(`FFCreator progress: ${(e.percent * 100) >> 0}%`));
                });
                creator.on('complete', e => {
                    resolve(true)
                    console.log(colors.magenta(`FFCreator completed: \n USEAGE: ${e.useage} \n PATH: ${e.output} `));
                });
            })
        }
        let status = await creator.complete()
        ctx.body = status ? {
            code: 200,
            message: '成功',
            data: {
                url: 'http://localhost:9926/hmm.mp4'
            }
        } : {
            code: 500,
            message: '生成失败',
            data: {}
        }
    }
};

module.exports = new CreateVideo()